<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams">
      <el-form-item label="商户名称" prop="name" class="mb-0px!">
        <el-input
          v-model="queryParams.name"
          class="!w-180px"
          clearable
          placeholder="请输入商户名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item class="mb-0px!">
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          type="primary"
          v-if="checkedTenants.length > 0 && type == 'component'"
          @click="handleUse"
        >
          选择商户
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <!-- 1. 多选模式（不能使用type="selection"，Element会忽略Header插槽） -->
      <el-table-column width="55" v-if="multiple">
        <template #header>
          <el-checkbox
            v-model="isCheckAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAll"
          />
        </template>
        <template #default="{ row }">
          <el-checkbox
            v-model="checkedStatus[row.id]"
            @change="(checked: boolean) => handleCheckOne(checked, row, true)"
          />
        </template>
      </el-table-column>
      <el-table-column label="ID" min-width="80" prop="id" />
      <el-table-column label="商户名称" min-width="250" prop="logo">
        <template #default="{ row }">
          <div class="flex flex-items-center">
            <el-image fit="cover" :src="row.avatar" class="flex-none w-50px h-50px rounded-4px" />
            <div class="ml-4 overflow-hidden">
              <el-tooltip effect="dark" :content="row.name" placement="top">
                <div>
                  {{ row.name }}
                </div>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商户类型" min-width="100" prop="tenantType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="scope.row.tenantType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="联系人" min-width="100" prop="contactName" />
      <el-table-column align="center" label="手机" min-width="100" prop="contactMobile" />

      <el-table-column align="center" label="开启状态" min-width="100" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" name="tenantList" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { propTypes } from '@/utils/propTypes'
import * as TenantApi from '@/api/system/tenant'
import { cloneDeep } from 'lodash-es'

type Tenant = Required<TenantApi.TenantVO>
// 用来处理是组件 还是页面
const props = defineProps({
  // 选中的商户列表
  selectTenantList: propTypes.array.def([]),
  type: propTypes.string.def('page'),
  TenantId: propTypes.number.def(undefined),
  // 多选模式
  multiple: propTypes.bool.def(false)
})

const emit = defineEmits(['selectTenants'])

const message = useMessage() // 消息弹窗

const total = ref(0) // 列表的总页数
const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,

  name: undefined,
  createTime: [],
  id: '' //商户
})
const queryFormRef = ref() // 搜索的表单

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
// 是否全选
const isCheckAll = ref(false)
// 全选框是否处于中间状态：不是全部选中 && 任意一个选中
const isIndeterminate = ref(false)
// 选中的商户
const checkedTenants = ref<Tenant[]>([])
// 选中状态：key为商户ID，value为是否选中
const checkedStatus = ref<Record<string, boolean>>({})

/** 全选/全不选 */
const handleCheckAll = (checked: boolean) => {
  isCheckAll.value = checked
  isIndeterminate.value = false

  list.value.forEach((tenant) => handleCheckOne(checked, tenant, false))
}
// 查找商户在已选中商户列表中的索引
const findCheckedIndex = (tenant: Tenant) =>
  checkedTenants.value.findIndex((item) => item.id === tenant.id)
/**
 * 选中一行
 * @param checked 是否选中
 * @param tenant 商户
 * @param isCalcCheckAll 是否计算全选
 */
const handleCheckOne = (checked: boolean, tenant: Tenant, isCalcCheckAll: boolean) => {
  if (checked) {
    checkedTenants.value.push(tenant)
    checkedStatus.value[tenant.id] = true
  } else {
    const index = findCheckedIndex(tenant)
    if (index > -1) {
      checkedTenants.value.splice(index, 1)
      checkedStatus.value[tenant.id] = false
      isCheckAll.value = false
    }
  }

  // 计算全选框状态
  if (isCalcCheckAll) {
    calculateIsCheckAll()
  }
}
// 计算全选框状态
const calculateIsCheckAll = () => {
  isCheckAll.value = list.value.every((tenant) => checkedStatus.value[tenant.id])
  // 计算中间状态：不是全部选中 && 任意一个选中
  isIndeterminate.value =
    !isCheckAll.value && list.value.some((tenant) => checkedStatus.value[tenant.id])
}
/** 使用选中 */
const handleUse = () => {
  if (checkedTenants.value.length === 0) {
    message.warning('请选择商户')
  } else {
    emit('selectTenants', checkedTenants)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.id = props.TenantId.toString()

    const data = await TenantApi.getTenantPage(queryParams)
    list.value = data.list
    total.value = data.total
    // checkbox绑定undefined会有问题，需要给一个bool值
    list.value.forEach(
      (tenant) => (checkedStatus.value[tenant.id] = checkedStatus.value[tenant.id] || false)
    )
    // 计算全选框状态
    calculateIsCheckAll()
  } finally {
    loading.value = false
  }
}

// 选中的商店列表
watch(
  () => props.selectTenantList,
  async () => {
    // 重置
    checkedTenants.value = []
    checkedStatus.value = {}
    isCheckAll.value = false
    isIndeterminate.value = false
    const deepCopyTenantList = cloneDeep(unref(props.selectTenantList)).map((item) => {
      return { id: item }
    }) as Tenant[]
    // 处理已选中
    if (deepCopyTenantList && deepCopyTenantList.length > 0) {
      checkedTenants.value = deepCopyTenantList as Tenant[]
      checkedStatus.value = Object.fromEntries(
        deepCopyTenantList.map((tenant) => [tenant.id, true])
      )
    }
  },
  { immediate: true }
)

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
